package com.zr.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zr.pojo.Permission;
import com.zr.pojo.Role;
import com.zr.pojo.User;
import com.zr.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * @auther zhaorui
 * @date 2019-12-03 - 0:44
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {

    //调用dubbo服务
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用dubbo服务  通过username获取user对象
        User user = userService.findByUsername(username);
        //判断user对象是否空
        if (user == null){
            //如果为空 返回null
            return null;
        }

        //创建 已授予权限 集合GrantedAuthority --> 已授予权限
        List<GrantedAuthority> list = new ArrayList<>();
        //获取user相对应的角色结合
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //添加到已授予权限中
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            //获取user相对应的角色 权限
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        org.springframework.security.core.userdetails.User user1 = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
        return user1;
    }
}
